import datetime
import os
import time

from PIL import Image, ImageDraw, ImageFont

import subprocess

from video_jian import web_auto_relase

# 使用合适的中文字体，例如微软雅黑或黑体
font_path = r'msyhbd.ttc'

def get_video_duration(input_video_path):
    command = [
        'ffprobe',
        '-v', 'error',
        '-show_entries', 'format=duration',
        '-of', 'default=noprint_wrappers=1:nokey=1',
        input_video_path
    ]
    print("执行命令:", command)
    result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,encoding='utf-8')

    if result.returncode != 0:
        raise ValueError(f"ffprobe 停止工作，错误信息：{result.stderr}")

    return float(result.stdout.strip())


def clip_video(input_video_path, output_video_path, start_time):
    """
    使用 ffmpeg 剪辑视频
    :param input_video_path: 输入视频文件路径
    :param output_video_path: 输出视频文件路径
    :param start_time: 剪辑开始时间，格式为 "HH:MM:SS" 或 "秒数"
    """
    # 将 start_time 转换为秒数
    if isinstance(start_time, str):
        # 如果是 HH:MM:SS 格式
        time_parts = start_time.split(':')
        if len(time_parts) == 3:  # HH:MM:SS
            start_seconds = int(time_parts[0]) * 3600 + int(time_parts[1]) * 60 + int(time_parts[2])
        elif len(time_parts) == 2:  # MM:SS
            start_seconds = int(time_parts[0]) * 60 + int(time_parts[1])
        else:  # 仅为秒数
            start_seconds = int(time_parts[0])
    else:
        start_seconds = int(start_time)  # 如果是直接以秒数给出

    # 获取视频时长
    duration = get_video_duration(input_video_path)  # 获取视频时长（以秒为单位）
    print('视频时长',duration)
    # 计算持续时间
    clip_duration = duration - start_seconds

    # 确保持续时间不为负数
    if clip_duration <= 0:
        raise ValueError("剪辑的开始时间超出了视频的总时长。")

    command = [
        'ffmpeg',
        '-i', input_video_path,
        '-ss', str(start_seconds),  # 开始时间
        '-t', str(clip_duration),  # 持续时间到视频结束
        '-c:v', 'libx264',  # 使用 libx264 编码视频
        '-preset', 'ultrafast',  # 设置编码速度
        '-crf', '23',  # 控制质量
        '-c:a', 'aac',  # 使用 AAC 编码音频
        #'-vf', 'scale=iw*0.5:ih*0.5',  # 缩小到原始分辨率的 0.5 倍
        output_video_path
    ]

    print("执行剪切命令:", command)  # 调试打印
    subprocess.run(command, check=True, encoding='utf-8')



# 在视频中截取图片,制作封面图片
# def create_thumbnail(input_video_path, output_thumbnail_path, time='00:03:00', title_text='经典动画'):
#     """
#     从视频中提取封面图并添加标题文字
#     :param input_video_path: 输入视频文件路径
#     :param output_thumbnail_path: 输出封面图片文件路径
#     :param time: 提取封面的时间，格式为 "HH:MM:SS" 或 "秒数"
#     :param title_text: 中心标题文字
#     """
#     # 提取视频的指定帧
#     command = [
#         'ffmpeg',
#         '-i', input_video_path,
#         '-ss', str(time),  # 提取时间
#         '-vframes', '1',   # 只提取一帧
#         output_thumbnail_path
#     ]
#     print("执行提取指定帧命令:", command)  # 调试打印
#     subprocess.run(command, check=True, encoding='utf-8')
#
#     # 创建新的输出文件名，添加 "_1" 后缀
#     base, ext = os.path.splitext(output_thumbnail_path)
#     new_output_thumbnail_path = f"{base}_1{ext}"
#
#     print('图片地址',output_thumbnail_path)
#     # 读取图片，获取尺寸
#     with Image.open(output_thumbnail_path) as img:
#         width, height = img.size
#
#         # 创建字体对象，设置字体大小
#         fontsize = int(height / 8)  # 根据高度设置字体大小
#         font = ImageFont.truetype(font_path, fontsize)  # 创建字体对象
#
#         # 创建绘图对象
#         draw = ImageDraw.Draw(img)
#
#         # 计算文字的宽度和高度，使用 textbbox 方法来获取文本的边界框
#         text_bbox = draw.textbbox((0, 0), title_text, font=font)
#         text_width = text_bbox[2] - text_bbox[0]  # 计算宽度
#         text_height = text_bbox[3] - text_bbox[1]  # 计算高度
#         # 计算居中位置
#         x = (width - text_width) / 2  # 文字在宽度中央
#         y = (height - text_height) * 0.5  # 文字在高度的80%处
#
#     # 在提取的封面图上添加标题文字
#     overlay_command = [
#         'ffmpeg',
#         '-i', output_thumbnail_path, # 输入图片地址
#          '-vf', (
#             f"drawtext=text='{title_text}':"
#             f"fontfile='{font_path}':"
#             f"fontcolor=yellow:fontsize={fontsize}:x={x}:y={y}:"
#             f"box=1:"  # 启用填充框
#             f"boxcolor=black@0.1:"  # 设置填充框颜色为半透明黑色
#             f"borderw=2:"  # 设置边框宽度
#             f"bordercolor=black"  # 设置边框颜色为黑色
#         ),
#         '-y',  # 强制覆盖输出文件
#         new_output_thumbnail_path  # 输出到新的文件
#     ]
#     print("执行缩略图叠加文本命令:", overlay_command)  # 调试打印
#     # 执行 FFmpeg 命令
#     try:
#         result = subprocess.run(overlay_command, check=True, encoding='utf-8', stderr=subprocess.PIPE)
#         print("FFmpeg 输出:", result.stderr)
#     except subprocess.CalledProcessError as e:
#         print(f"处理视频时发生错误: {e.stderr}")
#         return  # 返回以避免后续删除文件
#
#     # 删除源文件
#     os.remove(output_thumbnail_path)
#     print(f"已删除源文件: {output_thumbnail_path}")
#     return new_output_thumbnail_path


def add_text_as_first_frame_fast(input_video_path, text, output_video_path):
    """
    将图片作为第一帧插入视频，同时避免对原始视频重新编码，提高速度
    """
    """
        将图片替换为视频的第一帧
        """
    # # 1. 将图片和视频输出流拼接为合成流
    # subprocess.run([
    #     "ffmpeg", "-y","-i", input_video_path,  # 输入视频
    #     "-i", image_path,  # 输入图片
    #     "-filter_complex", "[1:v][0:v] overlay=0:0",  # 将图片覆盖到视频的第一帧
    #     "-c:v", "libx264",  # 编码为H.264
    #     "-crf", "23",  # 控制质量
    #     "-preset", "fast",  # 架构设置
    #     "-c:a", "copy",  # 保留音频不变
    #     output_video_path
    # ], check=True,encoding='utf-8')
    # 创建字体对象，设置字体大小

    subprocess.run([
        "ffmpeg", "-y",
        "-i", input_video_path,  # 输入视频
        "-vf",
        f"drawtext=fontfile='{font_path}':text={text}:fontcolor=yellow:fontsize=h/8:x=(w-text_w)/2:y=(h-text_h)/2:enable='eq(n\\,0)'",
        # 文本居中，第一帧显示
        "-c:v", "libx264",  # 编码为H.264
        "-crf", "23",  # 控制质量
        "-preset", "fast",  # 编码速度
        "-c:a", "copy",  # 保留音频
        output_video_path
    ], check=True,encoding='utf-8')





# num = 39  # 当前集数
def start(num,title):
    print("视频处理开始！", datetime.datetime.now())


    # 输入和输出路径设置
    video_file_path = 'G:\\BaiduNetdiskDownload\\少儿英语动画全集分级\\猫和老鼠 东北版\方言版3\\【动画】猫和老鼠东北方言版 [58集] 中文字幕\\'

    video_path = f'{video_file_path}猫和老鼠.  ({num}).mp4'  # 输入视频路径

    # 输出视频路径，带时间戳
    out_name = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')  # 格式化时间戳
    output_video_path = f'J:\\202410视频剪辑\\猫和老鼠\\python\\{num}_{out_name}.mp4'

    print('输入文件是:', video_path)
    print('输出文件是:', output_video_path)

    try:
        input_video = video_path  # 输入视频路径
        watermarked_output = output_video_path  # 添加水印后的输出视频路径
        clip_start_time = '00:00:30'  # 从第30秒开始剪辑

        # 剪辑视频
        clip_video(input_video, watermarked_output, clip_start_time)
        time.sleep(1)
        # 添加水印文字
        # add_watermark_text(watermarked_output, watermarked_output_new, title_text, position='top-left')

        # 添加完成之后,将watermarked_output文件删除

        # 创建封面图并添加中心标题
        # cover_img = create_thumbnail(watermarked_output, thumbnail_output, '00:03:00', title_text)  # 提取第3分钟的帧作为封面
        # time.sleep(1)

        watermarked_output_new = f'J:\\202410视频剪辑\\猫和老鼠\\python\\{num}_{out_name}_1.mp4'

        add_text_as_first_frame_fast(watermarked_output, title, watermarked_output_new)

        print("给视频加封面完成", watermarked_output_new)
        # 删除水印输出文件
        if os.path.exists(watermarked_output):
            os.remove(watermarked_output)
            print(f"已删除文件: {watermarked_output}")
        else:
            print(f"文件 {watermarked_output} 不存在，无法删除。")

        print("视频处理完成！", datetime.datetime.now())
        print("开始发布", watermarked_output_new)

        # 发三个视频.
        web_auto_relase.auto_release_kuaishou(watermarked_output_new, title,'User_Data_ks_anxinshuijiao')
        web_auto_relase.auto_release_kuaishou(watermarked_output_new, title)
        web_auto_relase.auto_release_douyin_tongman(watermarked_output_new, title)
        web_auto_relase.auto_release_douyin_tongman(watermarked_output_new, title, user_date='User_Data_Qinggan')

        print("视频发布完成！", datetime.datetime.now())
    except subprocess.CalledProcessError as e:
        print(f"处理视频时出现错误: {e}")
    except ValueError as ve:
        print(ve)


import os


def read_videos_by_numbers(folder_path, numbers):
    # 获取文件夹中的所有文件
    files = os.listdir(folder_path)

    # 过滤出符合格式的文件
    video_files = {int(file.split('.')[0]): file for file in files if file.endswith('.mp4')}

    # 根据传入的数字选择文件
    selected_files = [video_files[num] for num in numbers if num in video_files]

    return selected_files

# 方言版发布
def main():
    # 示例用法
    video_file_path = 'G:\\BaiduNetdiskDownload\\少儿英语动画全集分级\\猫和老鼠 东北版\方言版3\\【动画】猫和老鼠东北方言版 [58集] 中文字幕\\'

    folder_path = video_file_path  # 替换为你的文件夹路径
    numbers = [5, 6, 7, 8]  # 传入的数字列表
    selected_files = read_videos_by_numbers(folder_path, numbers)
    for file in selected_files:
        print(file)
        title = file.split('.')[1]
        title=title.replace(' ','')
        print("视频处理开始！", datetime.datetime.now())
        video_path = video_file_path+file  # 输入视频路径

        # 输出视频路径，带时间戳
        out_name = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')  # 格式化时间戳
        output_video_path = f'J:\\202410视频剪辑\\猫和老鼠\\python\\{title}_{out_name}.mp4'

        print('输入文件是:', video_path)
        print('输出文件是:', output_video_path)

        try:
            input_video = video_path  # 输入视频路径
            watermarked_output = output_video_path  # 添加水印后的输出视频路径
            clip_start_time = '00:00:17'  # 从第30秒开始剪辑

            # 剪辑视频
            clip_video(input_video, watermarked_output, clip_start_time)
            time.sleep(1)
            # 添加水印文字
            # add_watermark_text(watermarked_output, watermarked_output_new, title_text, position='top-left')

            # 添加完成之后,将watermarked_output文件删除

            # 创建封面图并添加中心标题
            # cover_img = create_thumbnail(watermarked_output, thumbnail_output, '00:03:00', title_text)  # 提取第3分钟的帧作为封面
            # time.sleep(1)

            watermarked_output_new = f'J:\\202410视频剪辑\\猫和老鼠\\python\\{title}_{out_name}_1.mp4'

            add_text_as_first_frame_fast(watermarked_output, title, watermarked_output_new)

            print("给视频加封面完成", watermarked_output_new)
            # 删除水印输出文件
            if os.path.exists(watermarked_output):
                os.remove(watermarked_output)
                print(f"已删除文件: {watermarked_output}")
            else:
                print(f"文件 {watermarked_output} 不存在，无法删除。")

            print("视频处理完成！", datetime.datetime.now())
            print("开始发布", watermarked_output_new)

            # 发三个视频.

            # 发三个视频.
            web_auto_relase.auto_release_kuaishou(watermarked_output_new, title, 'User_Data_ks_anxinshuijiao')
            web_auto_relase.auto_release_kuaishou(watermarked_output_new, title)
            web_auto_relase.auto_release_douyin_tongman(watermarked_output_new, title)
            web_auto_relase.auto_release_douyin_tongman(watermarked_output_new, title, user_date='User_Data_Qinggan')

            print("视频发布完成！", datetime.datetime.now())
        except subprocess.CalledProcessError as e:
            print(f"处理视频时出现错误: {e}")
        except ValueError as ve:
            print(ve)



# 示例使用
if __name__ == "__main__":
    main()
    # add_image_as_first_frame_fast('J:\\202410视频剪辑\\猫和老鼠\\python\\75_20241231_144118_1.mp4',
    #                               '猫和老鼠来了',
    #                               'J:\\202410视频剪辑\\猫和老鼠\\python\\75_20241231_144118_2.mp4')
    #auto_relea
    #
